<template>
  <div class="app-container">
    <div class="title-icon">
      <i class="iconfont iconhelp" @click="preview"></i>
    </div>
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="分类名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="visible">
        <el-select v-model="queryParams.visible" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in visibleOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:businessCategory:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table
      stripe
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" prop="menuName" />
      <el-table-column label="业务编码" prop="code" width="100"/>
      <el-table-column label="报告类型" prop="reportName" />
      <el-table-column label="报告号申请" prop="reportNoApply" width="100"/>
      <el-table-column label="排序" align="center" prop="orderNum" width="50"/>
      <el-table-column label="状态" align="center" prop="visible" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.visible==0">正常</span>
          <span v-else>停用</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="涉及项目阶段" align="center" prop="section" />
      <el-table-column label="备注" align="center" prop="remark" width="200"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.children.length==0"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="funHandleUpdate(scope.row)"
            v-hasPermi="['system:businessCategory:edit']"
          >功能权限</el-button>
          <el-button
            v-if="scope.row.children.length==0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="funHandleReportUpdate(scope.row)"
            v-hasPermi="['system:businessCategory:edit']"
          >报告类型</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:businessCategory:edit']"
          >编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改业务类别管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="98px">
        <el-form-item label="分类名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="上级分类" prop="parentId">
          <treeselect v-model="form.parentId" :options="businesstypes" placeholder="请选择上级分类" />
        </el-form-item>
        <el-form-item label="业务编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入业务编码" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" placeholder="请输入排序" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="状态" prop="visible">
          <el-radio-group v-model="form.visible">
            <el-radio
              v-for="dict in visibleOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="报告号申请" prop="reportNoApply">
          <el-select
            v-model="form.reportNoApply"
            placeholder="请选择"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option
              v-for="item in reportNoApplyOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="涉及项目阶段" prop="section">
          <el-select
            v-model="form.section"
            placeholder="请选择"
            clearable
            size="small"
            style="width: 240px"
            multiple
          >
            <el-option
              v-for="item in sectionOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 功能权限对话框 -->
    <el-dialog :title="funTitle" :visible.sync="funOpen" width="500px">
      <el-form ref="funForm" :model="funForm" label-width="80px">
        <el-form-item label="分类名称" prop="menuName">
          <el-input :disabled="true" v-model="funForm.menuName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="功能权限" prop="menuId">
          <el-select v-model="funForm.menuId" filterable placeholder="请选择">
            <el-option
              v-for="item in funcOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="funSubmitForm">确 定</el-button>
        <el-button @click="funCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 报告类型对话框 -->
    <el-dialog :title="reportTypeTitle" :visible.sync="reportFunOpen" width="500px">
      <el-form ref="reportFunForm" :model="reportFunForm" label-width="80px">
        
        <el-table :data="reportFunForm" style="width: 100%">
            <el-table-column prop="reportType" label="报告类型">
              <template slot-scope="scope">
                <el-input clearable v-model="scope.row.reportType"></el-input>
              </template>
            </el-table-column>
            <el-table-column width="80" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteListRow(scope.$index, reportFunForm)"
                  type="text"
                  size="small"
                >移除</el-button>
              </template>
            </el-table-column>
        </el-table>
        <div>
          <el-button type="primary" @click="addListRow()">添加一行</el-button>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="funReportSubmitForm">确 定</el-button>
        <el-button @click="funReportCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  exportCategory,
  treeselect,
  getFunOptions,
  bindMenus
} from "@/api/system/business_category";
import {
  listType,
  delType,
  addType
} from "@/api/system/reportType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "BusinessCategory",
  components: { Treeselect },
  data () {
    return {
      reportFunForm:undefined,
      manualPreviewUrl: null,
      openPreview: false,
      // 遮罩层
      loading: true,
      reportNoApplyOptions:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 业务类别管理表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      funTitle: "",
      reportTypeTitle:"",
      businessTypeId:"",
      // 是否显示弹出层
      open: false,
      funOpen: false,
      reportFunOpen:false,
      funcOptions: false,
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined
      },
      // 表单参数
      form: {},
      funForm: {},
      // 表单校验
      rules: {
        menuName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ],
        visible: [{ required: true, message: "状态不能为空", trigger: "blur" }]
      },
      // 日期范围
      dateRange: [],
      businesstypes: [],
      sectionOptions:[],
      visibleOptions: [
        {
          dictValue: "0",
          dictLabel: "正常"
        },
        {
          dictValue: "1",
          dictLabel: "停用"
        }
      ]
    };
  },
  created () {
    
    this.getTreeselect();
    this.getFunOptions();
    this.getAllList();
    this.getDicts("involve_project_section").then((response) => {
      this.sectionOptions = response.data;
    });
    
  },
  methods: {
    getFunOptions () {
      getFunOptions().then(response => {
        this.funcOptions = response.data;
      });
    },
    preview () {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}系统管理/业务类别管理.xlsx`
      )}&name=${encodeURIComponent("业务类别管理.xlsx")}`;
    },
    getAllList(){
      //行业类别
      this.getDicts('bms_report_apply').then(response => {
        this.reportNoApplyOptions = response.data
        this.getList();
      }); 
    },
    /** 查询业务类别管理列表 */
    getList () {

      this.loading = true;
      var reportNoApplyOptions = this.reportNoApplyOptions;
      listCategory(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          response.data.forEach(item=>{
            if(item.reportNoApply){
              reportNoApplyOptions.forEach(it=>{
              if(item.reportNoApply==it.dictValue){
                item.reportNoApply = it.dictLabel;
              }
              })
            }else{
              item.reportNoApply="";
            }
            
          });
          this.categoryList = this.handleTreeString(response.data, "guid");
          this.loading = false;
          this.getTreeselect();
        }
      );
    },
    /*查询业务类别下拉树结构 */
    getTreeselect () {
      treeselect().then(response => {
        this.businesstypes = [];
        const businesstype = { id: "0", label: "主分类", children: [] };
        businesstype.children = this.handleTreeString(response.data, "menuId");
        this.businesstypes.push(businesstype);
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    funCancel () {
      this.funOpen = false;
      this.resetFun();
    },
    funReportCancel(){
      this.reportFunOpen = false;
      this.resetReportFun();
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        menuName: undefined,
        parentId: undefined,
        orderNum: undefined,
        visible: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    resetFun () {
      this.funForm = {
        id: undefined,
        menuName: undefined,
        menuId: undefined
      };
      this.resetForm("funForm");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加业务类别管理";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids;
      getCategory(id).then(response => {
        this.form = response.data;
        if(this.form && this.form.section){
          this.form.section=this.form.section.split(";");
        }
        this.open = true;
        this.title = "修改业务类别管理";
      });
    },
    /*功能权限 */
    funHandleUpdate (row) {
      this.resetFun();
      const id = row.id || this.ids;
      getCategory(id).then(response => {
        this.funForm = response.data;
        this.funOpen = true;
        this.title = "功能权限";
      });
    },
    funHandleReportUpdate(row){
      this.resetReportFun();
      this.businessTypeId = row.guid;
      var rParam={
        businessTypeId:this.businessTypeId
      };

      listType(rParam).then(res=>{
        this.reportFunForm = res.data;
        this.reportFunOpen = true;
        this.reportTypeTitle = "报告类型修改";
        
      });

    },
    resetReportFun () {
      this.reportFunForm = {
        /*id: undefined,
        menuName: undefined,
        menuId: undefined*/
      };
      this.resetForm("reportFunForm");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            debugger
            var reqParams = this.form;
            reqParams.section = reqParams.section.join(";");
            updateCategory(reqParams).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            var reqParams = this.form;
            reqParams.section = reqParams.section.join(";");
            addCategory(reqParams).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    funSubmitForm: function () {
      this.$refs["funForm"].validate(valid => {

        if (valid) {
          if (this.funForm.id != undefined) {

            updateCategory(this.funForm).then(response => {
              if (response.code === 200) {
                this.msgSuccess("设置成功");
                this.funOpen = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    funReportSubmitForm:function(){
      debugger
      console.log(this.reportFunForm);

      if(this.reportFunForm && this.reportFunForm.length>0){
        var flag = true;
        this.reportFunForm.forEach(item => {
          if(!item.reportType){
            flag = false; 
          }
        });
        if(!flag){
          this.msgError("报告类型不能为空！");
          return;
        }
        
        addType(JSON.stringify(this.reportFunForm)).then(res=>{
          if(res.code===200){
            this.getList();
            this.msgSuccess("保存成功");
          }else{
            this.msgError("保存失败");
          }
          this.reportFunOpen = false;
        });
        
      }else{//删除所有报告类型
        this.reportFunOpen = false;
        delType(this.businessTypeId).then(res=>{
          if(res.code===200){
            this.getList();
            this.msgSuccess("保存成功");
          }else{
            this.msgError("保存失败");
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除业务类别管理编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function () {
          return delCategory(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    /** 导出按钮操作 */
    handleExport () {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有业务类别管理数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function () {
          return exportCategory(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    deleteListRow (index, rows) {
      rows.splice(index, 1);
    },
    addListRow () {
      this.reportFunForm.push({
        reportType: "",
        reportId:"",
        businessTypeId:this.businessTypeId
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.title-icon {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
  margin-bottom: 10px;
  .iconhelp {
    font-size: 18px;
  }
}
</style>

